package com.youlin.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.youlin.dto.BaseDataResDto;
import com.youlin.dto.BaseResDto;
import com.youlin.dto.Status;
import com.youlin.dto.req.*;
import com.youlin.dto.res.*;
import com.youlin.entities.*;
import com.youlin.mapper.BygDeadManMapper;
import com.youlin.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlin.untils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.jms.TextMessage;
import javax.jms.Topic;
import java.lang.ref.SoftReference;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class BygDeadManServiceImpl extends ServiceImpl<BygDeadManMapper, BygDeadMan> implements BygDeadManService {

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private MyCacheUtil myCacheUtil;
    @Autowired
    private BygAppointmentService bygAppointmentService;
    @Autowired
    private BygTextTemplateService bygTextTemplateService;
    @Autowired
    private BygBgTemplateService bygBgTemplateService;
    @Autowired
    private BygMusicTemplateService bygMusicTemplateService;
    @Autowired
    private BygPhotoService bygPhotoService;
    @Autowired
    private BygSignInService bygSignInService;
    @Autowired
    private BygSignInHistoryService bygSignInHistoryService;
    @Autowired
    private BygSignInTemplateService bygSignInTemplateService;
    @Autowired
    private BygAppInfoService bygAppInfoService;
    @Autowired
    private BygFarewellHallService bygFarewellHallService;
    @Autowired
    private ConcurrentHashMap<String, SoftReference<String>> dmCMap;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private Topic dmTopic;

    @Override
    public BaseDataResDto<DeadManResDto> findDmByAmUuIdAtSignIn(String amUuId, String version) {
        try {
            String deadManResJson = myCacheUtil.getFromCache(dmCMap, MyEnum.AMUUID_DM,
                    amUuId, MyEnum.AMBF, String.class, MyEnum.DMLOCK, () -> {

                        DeadManResDto finalDeadManRes = new DeadManResDto();

                        CompletableFuture<BygDeadMan> dmFuture = CompletableFuture.supplyAsync(() -> {
                            BygAppointment appointment = bygAppointmentService.findAppointmentByUuId(amUuId);
                            if (appointment == null) throw new ParamErrorExpectation();
                            BygDeadMan deadMan = getById(appointment.getDmId());
                            finalDeadManRes.setCoverUrl(deadMan.getCoverUrl())
                                    .setDeadBirthday(deadMan.getBirthday()).setAmId(appointment.getId())
                                    .setStatus(appointment.getStatus()).setDeadGender(deadMan.getGender())
                                    .setHeadUrl(deadMan.getHeadUrl()).setDeadDeadday(deadMan.getDeadday())
                                    .setLifeStory(deadMan.getLifeStory1()).setDeadName(deadMan.getName())
                                    .setLifeTitle1(deadMan.getLifeTitle1()).setLifeStory1(deadMan.getLifeStory1())
                                    .setLifeTitle2(deadMan.getLifeTitle2()).setLifeStory2(deadMan.getLifeStory2());
                            return deadMan;
                        }, threadPoolExecutor);

                        CompletableFuture<Void> musicFuture = dmFuture.thenAcceptAsync(deadMan -> {
                            BygMusicTemplate musicTemplate = bygMusicTemplateService.getById(deadMan.getMsId());
                            finalDeadManRes.setMusicUrl(musicTemplate.getUrl());
                        }, threadPoolExecutor);

                        CompletableFuture<Void> txFuture = dmFuture.thenAcceptAsync(deadMan -> {
                            List<BygTextTemplate> textTemplates = bygTextTemplateService
                                    .list(new QueryWrapper<BygTextTemplate>().eq("name", deadMan.getTxName()));
                            for (BygTextTemplate tx : textTemplates) {
                                finalDeadManRes.setTxName(tx.getName());
                                if (tx.getType() == MyEnum.TX_TYPE_HEAD.getValue())
                                    finalDeadManRes.setHeadTx(tx.getContent());
                                if (tx.getType() == MyEnum.TX_TYPE_LIFE.getValue())
                                    finalDeadManRes.setLifeStoryTx(tx.getContent());
                            }
                        }, threadPoolExecutor);

                        CompletableFuture<Void> bgFuture = dmFuture.thenAcceptAsync(deadMan -> {
                            List<BygBgTemplate> bygBgTemplates = bygBgTemplateService.list(Wrappers
                                    .lambdaQuery(BygBgTemplate.class).eq(BygBgTemplate::getBgId, deadMan.getBgId()));
                            Map<String, BygBgTemplate> pBrMap = Maps.newHashMap();
                            List<BygBgTemplate> pBgList = Lists.newArrayList();
                            BygBgTemplate siBg = null;
                            for (BygBgTemplate bg : bygBgTemplates) {
                                if (bg.getType() == MyEnum.BG_COLOR.getValue())
                                    finalDeadManRes.setBgColor(bg.getText());
                                if (bg.getType() == MyEnum.BG_TYPE_HEAD.getValue())
                                    finalDeadManRes.setHeadBgUrl(bg.getUrl());
                                if (bg.getType() == MyEnum.BG_TYPE_HEAD_BR.getValue())
                                    finalDeadManRes.setHeadBrUrl(bg.getUrl());
                                if (bg.getType() == MyEnum.BG_TYPE_LIFE.getValue()) {
                                    if (bg.getText().contains("no-1")) {
                                        finalDeadManRes.setLifeStoryBgUrl(bg.getUrl());
                                        finalDeadManRes.setLifeStoryBgUrl1(bg.getUrl());
                                    }
                                    if (bg.getText().contains("no-2")) finalDeadManRes.setLifeStoryBgUrl2(bg.getUrl());
                                }
                                if (bg.getType() == MyEnum.BG_TYPE_FTX.getValue())
                                    finalDeadManRes.setFTexUrl(bg.getUrl());
                                if (bg.getType() == MyEnum.BG_TYPE_PHOTO_BR.getValue()) pBrMap.put(bg.getWh(), bg);
                                if (bg.getType() == MyEnum.BG_TYPE_PHOTO.getValue()) pBgList.add(bg);
                                if (bg.getType() == MyEnum.BG_TYPE_SI.getValue()) siBg = bg;
                            }
                            Map<Integer, List<BygBgTemplate>> pBgListMap = pBgList
                                    .parallelStream().collect(Collectors.groupingBy(BygBgTemplate::getPid));
                            AtomicInteger aIndex = new AtomicInteger(0);
                            LambdaQueryWrapper<BygPhoto> wrapper = Wrappers.lambdaQuery(BygPhoto.class)
                                    .eq(BygPhoto::getDmId, deadMan.getId()).orderByAsc(BygPhoto::getNo);
                            List<PhotoResDto> photoResList = bygPhotoService.list(wrapper).stream().map(p -> {
                                String wh = p.getWh();
                                BygBgTemplate pBr = pBrMap.get(wh);
                                List<BygBgTemplate> ppBgList = pBgListMap.get(pBr.getId());
                                Integer index = null;
                                if (wh.equals("520*700")) index = aIndex.getAndIncrement() % ppBgList.size();
                                if (wh.equals("625*415")) index = aIndex.getAndIncrement() % ppBgList.size();
                                if (wh.equals("530*620")) index = aIndex.getAndIncrement() % ppBgList.size();
                                BygBgTemplate pBg = ppBgList.get(index);
                                return new PhotoResDto().setPhotoUrl(p.getPhotoUrl()).setPhotoBrUrl(pBr.getUrl())
                                        .setRemark(p.getRemark()).setPhotoBgUrl(pBg.getUrl()).setWh(p.getWh());
                            }).collect(Collectors.toList());
                            finalDeadManRes.setPhotos(photoResList);
                            if (siBg != null) {
                                finalDeadManRes.setSignInBgUrl(siBg.getUrl());
                                bygBgTemplates.parallelStream()
                                        .filter(bg -> bg.getType() == MyEnum.BG_TYPE_SIFB.getValue())
                                        .findFirst().ifPresent(bg -> finalDeadManRes.setSignInBrUrl(bg.getUrl()));
                                Map<Integer, String> siflUrls = bygBgTemplates.parallelStream()
                                        .filter(bg -> bg.getType() == MyEnum.BG_TYPE_SIFL.getValue())
                                        .collect(Collectors.toMap(BygBgTemplate::getPid, bg -> bg.getUrl()));
                                // 献花模板存在历史数据以兼容旧版本小程序
                                if (siflUrls.size() > 9) siflUrls = bygBgTemplates.parallelStream()
                                        .filter(bg -> bg.getType() == MyEnum.BG_TYPE_SIFL.getValue()
                                                && version.equals(bg.getWh()))
                                        .collect(Collectors.toMap(BygBgTemplate::getPid, bg -> bg.getUrl()));
                                Long sifCount = bygBgTemplates.parallelStream()
                                        .filter(bg -> bg.getType() == MyEnum.BG_TYPE_SIF.getValue())
                                        .collect(Collectors.counting());
                                Map<Integer, BygBgTemplate> sifMap = bygBgTemplates.parallelStream()
                                        .filter(bg -> bg.getType() == MyEnum.BG_TYPE_SIF.getValue()
                                                && (sifCount > 9 ? version.equals(bg.getWh()) : true))
                                        .collect(Collectors.toMap(BygBgTemplate::getPid, bg -> bg));
                                Map<Integer, String> finalSiflUrls = siflUrls;
                                 // sifhCount > 9 说明献花模板存在历史数据以兼容旧版本小程序
                                Long sifhCount = bygBgTemplates.parallelStream()
                                        .filter(bg -> bg.getType().intValue() == MyEnum.BG_TYPE_SIFH.getValue())
                                        .collect(Collectors.counting());
                                List<BgSitResDto> sifs = bygBgTemplates.parallelStream()
                                        .filter(bg -> bg.getType().intValue() == MyEnum.BG_TYPE_SIFH.getValue()
                                                && (sifhCount > 9 ? version.equals(bg.getWh()) : true))
                                        .map(bg -> new BgSitResDto().setHighUrl(bg.getUrl()).setLowUrl(finalSiflUrls.get(bg.getId()))
                                                .setText(bg.getText()).setFlowerUrl(sifMap.get(bg.getId()).getUrl())
                                                .setSitId(Integer.parseInt(sifMap.get(bg.getId()).getText())))
                                        .collect(Collectors.toList());
                                finalDeadManRes.setSifs(sifs);
                            }
                        }, threadPoolExecutor);

                        return CompletableFuture.allOf(musicFuture, txFuture, bgFuture)
                                .thenApplyAsync(f -> JSON.toJSONString(finalDeadManRes), threadPoolExecutor).join();
                    });

            DeadManResDto deadManResDto = JSON.parseObject(deadManResJson, DeadManResDto.class).setSiId(Md5Util.getUUID());
            return new BaseDataResDto<DeadManResDto>(Status.SUCCESS).setData(deadManResDto);
        } catch (ParamErrorExpectation e) {
            e.printStackTrace();
            return new BaseDataResDto<>(Status.PARAMETERERROR);
        } catch (Exception e) {
            e.printStackTrace();
            if (e.getCause() instanceof ParamErrorExpectation)
                return new BaseDataResDto<>(Status.PARAMETERERROR);
            return new BaseDataResDto<>(Status.ERROR);
        }
    }

    @Override
    public BaseDataResDto<DmFinallyResDto> findDmByAmUuIdAtFinally(String amUuId) {

        // 获取 告别会信息
        LambdaQueryWrapper<BygAppointment> wrapper = Wrappers
                .lambdaQuery(BygAppointment.class).eq(BygAppointment::getUuId, amUuId);
        BygAppointment appointment = bygAppointmentService.getOne(wrapper);
        if (appointment == null) return new BaseDataResDto<>(Status.PARAMETERERROR);

        // 异步获取 单位信息
        CompletableFuture<BygAppInfo> appFuture = CompletableFuture.supplyAsync(() -> {
            BygFarewellHall farewellHall = bygFarewellHallService.getById(appointment.getFhId());
            return bygAppInfoService.getById(farewellHall.getUnitId());
        });

        // 异步获取 逝者信息
        CompletableFuture<BygDeadMan> dmFuture = CompletableFuture.supplyAsync(() -> getById(appointment.getDmId()));

        // 异步获取 北京音乐
        CompletableFuture<BygMusicTemplate> mscFuture = dmFuture.thenApplyAsync((dm) -> bygMusicTemplateService.getById(dm.getMsId()));

        // 异步获取 背景列表
        CompletableFuture<List<BygBgTemplate>> bgFuture = CompletableFuture.supplyAsync(() -> {
            BygDeadMan deadMan = dmFuture.join();
            LambdaQueryWrapper<BygBgTemplate> bgWrapper = Wrappers.lambdaQuery(BygBgTemplate.class)
                    .eq(BygBgTemplate::getBgId, deadMan.getBgId());
            return bygBgTemplateService.list(bgWrapper);
        });

        // 异步获取 来宾签到时使用最多的签到模板ID(九型人格)
        CompletableFuture<Integer> sitIdFuture = CompletableFuture.supplyAsync(() -> {
            List<BygSignInTemplate> signInTemplates = bygSignInTemplateService.list().parallelStream()
                    .sorted(Comparator.comparingInt(BygSignInTemplate::getWeight)).collect(Collectors.toList());
            Map<Integer, Integer> sitMap = signInTemplates.parallelStream()
                    .collect(Collectors.toMap(BygSignInTemplate::getId, BygSignInTemplate::getWeight));

            // 获取来宾签到时使用最多的签到模板ID
            // select from byg_sign_in
            Integer sitIdSignIn = BaseService.getSitId(BygSignIn.class, BygSignIn::getSitId,
                    BygSignIn::getAmUuId, appointment.getUuId(), bygSignInService, sitMap);
            if (sitIdSignIn != null) return sitIdSignIn;

            // select from byg_sign_in_history
            sitIdSignIn = BaseService.getSitId(BygSignInHistory.class, BygSignInHistory::getSitId,
                    BygSignInHistory::getAmUuId, appointment.getUuId(), bygSignInHistoryService, sitMap);
            if (sitIdSignIn != null) return sitIdSignIn;

            // 获取默认排序比重第一的签到模板ID
            return signInTemplates.stream().findFirst().get().getId();
        });

        // 异步获取 逝者家庭照数据
        CompletableFuture<PhotoResDto> photoFuture = CompletableFuture.supplyAsync(() -> {
            LambdaQueryWrapper<BygPhoto> pWrapper = Wrappers.lambdaQuery(BygPhoto.class)
                    .eq(BygPhoto::getDmId, appointment.getDmId()).eq(BygPhoto::getIsFamily, true);
            BygPhoto photo = bygPhotoService.getOne(pWrapper);
            PhotoResDto photoResDto = new PhotoResDto();
            if (photo != null) photoResDto.setWh(photo.getWh())
                    .setPhotoUrl(photo.getPhotoUrl()).setRemark(photo.getRemark());
            else photoResDto.setPhotoUrl(dmFuture.join().getHeadUrl());
            bgFuture.join().parallelStream().forEach(bg -> {
                if (photo == null && bg.getType() == MyEnum.BG_TYPE_HEAD_BR.getValue())
                    photoResDto.setPhotoBrUrl(bg.getUrl());
                if (bg.getType() == MyEnum.BG_TYPE_FAMILY.getValue()) photoResDto.setPhotoBgUrl(bg.getUrl());
                if (photo != null && bg.getType() == MyEnum.BG_TYPE_PHOTO_BR.getValue() &&
                        bg.getWh().equals(photo.getWh())) photoResDto.setPhotoBrUrl(bg.getUrl());
            });
            return photoResDto;
        });

        // 异步获取 逝者相册数据
        CompletableFuture<List<PhotoResDto>> photoListFuture = CompletableFuture.supplyAsync(() -> {
            Map<String, BygBgTemplate> pBrMap = bgFuture.join().parallelStream()
                    .filter(bg -> bg.getType() == MyEnum.BG_TYPE_PHOTO_BR.getValue())
                    .collect(Collectors.toMap(BygBgTemplate::getWh, Function.identity()));

            Map<Integer, List<BygBgTemplate>> pBgListMap = bgFuture.join().parallelStream()
                    .filter(bg -> bg.getType() == MyEnum.BG_TYPE_PHOTO.getValue())
                    .collect(Collectors.groupingBy(BygBgTemplate::getPid));

            AtomicInteger aIndex = new AtomicInteger(0);
            LambdaQueryWrapper<BygPhoto> photoWrapper = Wrappers.lambdaQuery(BygPhoto.class)
                    .eq(BygPhoto::getDmId, appointment.getDmId()).orderByAsc(BygPhoto::getNo);
            return bygPhotoService.list(photoWrapper).stream().map(p -> {
                String wh = p.getWh();
                BygBgTemplate pBr = pBrMap.get(wh);
                List<BygBgTemplate> ppBgList = pBgListMap.get(pBr.getId());
                Integer index = null;
                if (wh.equals("520*700")) index = aIndex.getAndIncrement() % ppBgList.size();
                if (wh.equals("625*415")) index = aIndex.getAndIncrement() % ppBgList.size();
                if (wh.equals("530*620")) index = aIndex.getAndIncrement() % ppBgList.size();
                BygBgTemplate pBg = ppBgList.get(index);
                return new PhotoResDto().setPhotoUrl(p.getPhotoUrl()).setPhotoBrUrl(pBr.getUrl())
                        .setRemark(p.getRemark()).setPhotoBgUrl(pBg.getUrl()).setWh(p.getWh());
            }).collect(Collectors.toList());
        });

        // 异步操作 组合请求数据
        return CompletableFuture.supplyAsync(() -> {
            BygBgTemplate sibg = bgFuture.join().parallelStream()
                    .filter(bg -> bg.getType().equals(sitIdFuture.join())).findFirst().get();
            BygBgTemplate siFixedbg = bgFuture.join().parallelStream()
                    .filter(bg -> bg.getPid().intValue() == sibg.getId()).findFirst().get();
            BygDeadMan deadMan = dmFuture.join();
            BygAppInfo appInfo = appFuture.join();
            BygMusicTemplate music = mscFuture.join();
            List<PhotoResDto> photoResDtoList = photoListFuture.join();
            DmFinallyResDto data = new DmFinallyResDto().setSiBgUrl(sibg.getUrl())
                    .setMusicUrl(music.getUrl()).setCTemplateId(appInfo.getCustomId())
                    .setSiBgUrlFixed(siFixedbg.getUrl()).setCoverUrl(deadMan.getCoverUrl())
                    .setDeadBirthday(deadMan.getBirthday()).setDeadDeadday(deadMan.getDeadday())
                    .setLifeTitle1(deadMan.getLifeTitle1()).setLifeStory1(deadMan.getLifeStory1())
                    .setLifeTitle2(deadMan.getLifeTitle2()).setLifeStory2(deadMan.getLifeStory2())
                    .setDmName(deadMan.getName()).setDmGender(deadMan.getGender()).setPhotos(photoResDtoList)
                    .setPhoto(photoFuture.join()).setSiBgText(sibg.getText()).setHeadUrl(deadMan.getHeadUrl());
            bgFuture.join().parallelStream().forEach(bg -> {
                if (bg.getType() == MyEnum.BG_TYPE_LIFE.getValue()) {
                    if (bg.getText().contains("no-1")) data.setLifeStoryBgUrl1(bg.getUrl());
                    if (bg.getText().contains("no-2")) data.setLifeStoryBgUrl2(bg.getUrl());
                }
                if (bg.getType() == MyEnum.BG_COLOR.getValue()) data.setBgColor(bg.getText());
                if (bg.getType() == MyEnum.BG_TYPE_HEAD.getValue()) data.setHeadBgUrl(bg.getUrl());
                if (bg.getType() == MyEnum.BG_TYPE_HEAD_BR.getValue()) data.setHeadBrUrl(bg.getUrl());
                if (bg.getType() == MyEnum.BG_TYPE_SINAME.getValue()) data.setSiNameUrl(bg.getUrl());
                if (bg.getType() == MyEnum.BG_TYPE_SICONTENT.getValue()) data.setSiContentUrl(bg.getUrl());
                if (bg.getType() == MyEnum.BG_TYPE_CBG.getValue()) data.setSiCbgUrl(bg.getUrl());
                if (bg.getType() == MyEnum.BG_TYPE_CBR.getValue()) data.setSiCbrUrl(bg.getUrl());
                if (bg.getType() == MyEnum.BG_TYPE_PTX.getValue()) data.setPTextUrl(bg.getUrl());
            });
            Integer showInfo = RedisUtil.getObject(redisTemplate, "SHOWINFO", Integer.class);
            return new BaseDataResDto<DmFinallyResDto>(Status.SUCCESS).setData(data.setShowInfo(showInfo));
        }).join();
    }

    @Override
    public BaseDataResDto<DMResDto> findDeadManById(String dmId) {
        BygDeadMan deadMan = getById(dmId);
        if (deadMan == null) return new BaseDataResDto<>(Status.PARAMETERERROR);
        DMResDto dmResDto = BaseService.copyProperties(deadMan, DMResDto.class);
        LambdaQueryWrapper<BygPhoto> wrapper = Wrappers.lambdaQuery(BygPhoto.class)
                .eq(BygPhoto::getDmId, dmId).orderByAsc(BygPhoto::getNo);
        List<PhotoReqDto> photos = bygPhotoService.list(wrapper).parallelStream()
                .map(p -> MyBeanUtil.copyProperties(p, PhotoReqDto.class)).collect(Collectors.toList());
        return new BaseDataResDto<DMResDto>(Status.SUCCESS).setData(dmResDto.setPhotos(photos));
    }

    @Override
    @Transactional
    public <T> BaseResDto<Status, String> editDeadManData(T data) {
        LambdaUpdateWrapper<BygDeadMan> updateWrapper = Wrappers.lambdaUpdate(BygDeadMan.class);
        Integer dmId = null;
        if (data instanceof EditDMDataReqDto) {
            EditDMDataReqDto editDMData = (EditDMDataReqDto) data;
            dmId = editDMData.getDmId();
            updateWrapper.set(BygDeadMan::getName, editDMData.getName())
                    .set(BygDeadMan::getCoverUrl, editDMData.getCoverUrl()).set(BygDeadMan::getHeadUrl, editDMData.getHeadUrl())
                    .set(BygDeadMan::getLifeTitle1, editDMData.getLifeTitle1()).set(BygDeadMan::getLifeStory1, editDMData.getLifeStory1())
                    .set(BygDeadMan::getLifeTitle2, editDMData.getLifeTitle2()).set(BygDeadMan::getLifeStory2, editDMData.getLifeStory2());
            BygDeadMan byId = getById(editDMData.getDmId());
            if (!editDMData.getName().equals(byId.getName()) || !editDMData.getHeadUrl().equals(byId.getHeadUrl())) {
                LambdaUpdateWrapper<BygAppointment> amWrapper = Wrappers.lambdaUpdate(BygAppointment.class)
                        .eq(BygAppointment::getDmId, editDMData.getDmId()).set(BygAppointment::getPosterUrl, null);
                if (!bygAppointmentService.update(amWrapper)) return new BaseResDto<>(Status.ERROR);
            }
        }
        if (data instanceof SetDMBgReqDto) {
            SetDMBgReqDto setDMBg = (SetDMBgReqDto) data;
            dmId = setDMBg.getDmId();
            updateWrapper.set(BygDeadMan::getBgId, setDMBg.getBgId());
        }
        if (data instanceof SetDMTXReqDto) {
            SetDMTXReqDto setDMTX = (SetDMTXReqDto) data;
            dmId = setDMTX.getDmId();
            updateWrapper.set(BygDeadMan::getTxName, setDMTX.getTxName());
        }
        if (data instanceof SetDMMsReqDto) {
            SetDMMsReqDto setDMMs = (SetDMMsReqDto) data;
            dmId = setDMMs.getDmId();
            updateWrapper.set(BygDeadMan::getMsId, setDMMs.getMsId());
        }

        updateWrapper.eq(BygDeadMan::getId, dmId).set(BygDeadMan::getUpdateTime, LocalDateTime.now());
        if (!update(updateWrapper)) return new BaseResDto<>(Status.ERROR);

        // 清除多负载的逝者信息本地缓存
        Integer finalDmId = dmId;
        CompletableFuture.runAsync(() -> {
            BygAppointment appointment = bygAppointmentService.getOne(
                    new QueryWrapper<BygAppointment>().eq("dm_id", finalDmId));
            jmsMessagingTemplate.convertAndSend(dmTopic, MyEnum.AMUUID_DM.getMessage() + appointment.getUuId());
        });

        return new BaseResDto<>(Status.SUCCESS);
    }

    @JmsListener(destination = "dmTopic")
    public void cleanDmCache(TextMessage textMessage) throws Exception {
        String finalCacheKey = textMessage.getText();
        MyCacheUtil.delInCache(dmCMap, finalCacheKey);
        redisTemplate.delete(finalCacheKey);
    }

    @JmsListener(destination = "dmLocalCacheTopic")
    public void cleanDmLocalCache(TextMessage textMessage) throws Exception {
        String finalCacheKey = textMessage.getText();
        MyCacheUtil.delInCache(dmCMap, finalCacheKey);
    }

}
